package controller

import (
	"ai-curd/controller/request"
	"ai-curd/controller/response"
	"ai-curd/oo"
	"ai-curd/repository"
	"ai-curd/repository/ent"
	entarticle "ai-curd/repository/ent/article"
	"github.com/gin-gonic/gin"
)

type Article struct {
	repo *repository.Article
}

func NewArticle(repo *repository.Article) *Article {
	ctr := new(Article)
	ctr.repo = repo
	return ctr
}

func (ctr *Article) One(c *gin.Context) (response.Data, error) {
	req := new(request.ArticleOne)
	if err := c.ShouldBind(req); err != nil {
		return nil, err
	}

	ooArticle := ctr.repo.Fetch(c.Request.Context(), req.ID)

	if ooArticle == nil {
		return nil, nil
	}

	return ooArticle.Mapper(), nil
}

func (ctr *Article) Many(c *gin.Context) (response.Data, error) {
	req := new(request.ArticleMany)
	if err := c.ShouldBind(req); err != nil {
		return nil, err
	}

	ooArticles := ctr.repo.FetchMany(c.Request.Context(), func(query *ent.ArticleQuery) {
		query.Where(entarticle.Category(req.Category))
	})
	return ooArticles.Mapper(), nil
}

func (ctr *Article) Create(c *gin.Context) (response.Data, error) {
	req := new(request.ArticleCreate)
	if err := c.ShouldBind(req); err != nil {
		return nil, err
	}

	cmdArticle := oo.NewArticle(req.Category)
	cmdArticle.SetCategory(req.Category)
	cmdArticle.SetTitle(req.Title)

	ooArticle := ctr.repo.Save(c.Request.Context(), cmdArticle)
	return ooArticle.Mapper(), nil
}

func (ctr *Article) Modify(c *gin.Context) (response.Data, error) {
	req := new(request.ArticleModify)
	if err := c.ShouldBind(req); err != nil {
		return nil, err
	}

	cmdArticle := oo.NewArticle(req.Category)
	cmdArticle.SetID(req.ID)
	cmdArticle.SetCategory(req.Category)
	cmdArticle.SetTitle(req.Title)

	return ctr.repo.Modify(c.Request.Context(), cmdArticle), nil
}
